from datetime import datetime
from .extensions import db
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

class User(db.Model, UserMixin):
    """用户模型"""
    __tablename__ = 'user'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False, comment='用户名')
    password = db.Column(db.String(100), nullable=False, comment='加密密码')
    email = db.Column(db.String(120), unique=True, nullable=True, comment='电子邮箱')
    phone = db.Column(db.String(20), nullable=True, comment='手机号码')
    is_admin = db.Column(db.Boolean, default=False, comment='是否管理员')
    last_login = db.Column(db.DateTime, nullable=True, comment='最后登录时间')
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow,
                         onupdate=datetime.utcnow, comment='更新时间')
    avatar_url = db.Column(db.String(255), nullable=True, comment='头像URL')
    status = db.Column(db.String(20), default='active',
                     comment='账户状态: active/inactive/suspended')

    # 关系定义
    user_borrow_records = db.relationship(
        'BorrowRecord',
        back_populates='borrower',
        foreign_keys='BorrowRecord.user_id',
        lazy=True
    )
    user_reservations = db.relationship(
        'Reservation',
        back_populates='reserver',
        foreign_keys='Reservation.user_id',
        lazy=True
    )
    user_notifications = db.relationship(
        'Notification',
        back_populates='receiver',
        lazy=True
    )
    submitted_return_requests = db.relationship(
        'ReturnRequest',
        back_populates='submitter',
        foreign_keys='ReturnRequest.user_id',
        lazy=True
    )
    processed_return_requests = db.relationship(
        'ReturnRequest',
        back_populates='processor',
        foreign_keys='ReturnRequest.admin_id',
        lazy=True
    )
    submitted_borrow_requests = db.relationship(
        'BorrowRequest',
        back_populates='requester',
        foreign_keys='BorrowRequest.user_id',
        lazy=True
    )
    processed_borrow_requests = db.relationship(
        'BorrowRequest',
        back_populates='approver',
        foreign_keys='BorrowRequest.processed_by',
        lazy=True
    )
    processed_records = db.relationship(
        'BorrowRecord',
        back_populates='record_processor',
        foreign_keys='BorrowRecord.processed_by',
        lazy=True
    )

    def __repr__(self):
        return f"<User {self.username}>"

    def set_password(self, password):
        """设置密码（自动加密）"""
        self.password = generate_password_hash(password)

    def check_password(self, password):
        """验证密码"""
        return check_password_hash(self.password, password)

class Book(db.Model):
    """图书模型"""
    __tablename__ = 'book'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False, index=True, comment='书名')
    author = db.Column(db.String(100), nullable=False, index=True, comment='作者')
    description = db.Column(db.Text, nullable=True, comment='图书描述')
    isbn = db.Column(db.String(20), unique=True, nullable=True, comment='ISBN号')
    publication_date = db.Column(db.Date, nullable=True, comment='出版日期')
    category = db.Column(db.String(50), nullable=True, index=True, comment='分类')
    status = db.Column(db.String(20), default='available', comment='当前状态')
    available_copies = db.Column(db.Integer, default=1, comment='可用副本数')
    total_copies = db.Column(db.Integer, default=1, comment='总副本数')
    cover_image = db.Column(db.String(255), nullable=True, comment='封面图片URL')
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='添加时间')

    # 关系定义
    book_borrow_records = db.relationship(
        'BorrowRecord',
        back_populates='book',
        foreign_keys='BorrowRecord.book_id',
        lazy=True
    )
    book_reservations = db.relationship(
        'Reservation',
        back_populates='book',
        foreign_keys='Reservation.book_id',
        lazy=True
    )
    book_borrow_requests = db.relationship(
        'BorrowRequest',
        back_populates='book',
        foreign_keys='BorrowRequest.book_id',
        lazy=True
    )

    def __repr__(self):
        return f"<Book {self.title} by {self.author}>"

    def is_available(self):
        """检查图书是否可借"""
        return self.available_copies > 0

class BorrowRecord(db.Model):
    """借阅记录模型"""
    __tablename__ = 'borrow_record'

    id = db.Column(db.Integer, primary_key=True)
    book_id = db.Column(db.Integer, db.ForeignKey('book.id'), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    borrow_date = db.Column(db.DateTime, default=datetime.utcnow, comment='借阅日期')
    due_date = db.Column(db.DateTime, nullable=True, comment='应还日期')
    return_date = db.Column(db.DateTime, nullable=True, comment='实际归还日期')
    status = db.Column(db.String(20), default='borrowed',
                     comment='状态: borrowed/returning/returned/overdue')
    renew_count = db.Column(db.Integer, default=0, comment='续借次数')
    processed_by = db.Column(db.Integer, db.ForeignKey('user.id'),
                           nullable=True, comment='处理人ID')

    # 关系定义
    book = db.relationship(
        'Book',
        back_populates='book_borrow_records',
        foreign_keys=[book_id]
    )
    borrower = db.relationship(
        'User',
        back_populates='user_borrow_records',
        foreign_keys=[user_id]
    )
    record_processor = db.relationship(
        'User',
        back_populates='processed_records',
        foreign_keys=[processed_by]
    )
    record_return_requests = db.relationship(
        'ReturnRequest',
        back_populates='borrow_record',
        foreign_keys='ReturnRequest.record_id',
        lazy=True
    )

    def __repr__(self):
        return f"<BorrowRecord #{self.id}>"

class Reservation(db.Model):
    """预约记录模型"""
    __tablename__ = 'reservation'

    id = db.Column(db.Integer, primary_key=True)
    book_id = db.Column(db.Integer, db.ForeignKey('book.id'), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    reservation_date = db.Column(db.DateTime, default=datetime.utcnow,
                               comment='预约日期')
    status = db.Column(db.String(20), default='pending',
                     comment='状态: pending/fulfilled/cancelled')
    notify_when_available = db.Column(db.Boolean, default=False,
                                    comment='可用时通知')
    expiry_date = db.Column(db.DateTime, nullable=True, comment='过期时间')

    # 关系定义
    book = db.relationship(
        'Book',
        back_populates='book_reservations',
        foreign_keys=[book_id]
    )
    reserver = db.relationship(
        'User',
        back_populates='user_reservations',
        foreign_keys=[user_id]
    )

    def __repr__(self):
        return f"<Reservation #{self.id}>"

class ReturnRequest(db.Model):
    """还书申请模型"""
    __tablename__ = 'return_request'

    id = db.Column(db.Integer, primary_key=True)
    record_id = db.Column(db.Integer, db.ForeignKey('borrow_record.id'), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    admin_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)
    request_time = db.Column(db.DateTime, default=datetime.utcnow, comment='申请时间')
    process_time = db.Column(db.DateTime, nullable=True, comment='处理时间')
    status = db.Column(db.String(20), default='pending', comment='状态: pending/approved/rejected')
    notes = db.Column(db.Text, nullable=True, comment='处理备注')

    # 关系定义
    borrow_record = db.relationship(
        'BorrowRecord',
        back_populates='record_return_requests',
        foreign_keys=[record_id]
    )
    submitter = db.relationship(
        'User',
        back_populates='submitted_return_requests',
        foreign_keys=[user_id]
    )
    processor = db.relationship(
        'User',
        back_populates='processed_return_requests',
        foreign_keys=[admin_id]
    )

    def __repr__(self):
        return f"<ReturnRequest #{self.id}>"

class BorrowRequest(db.Model):
    """借阅申请模型"""
    __tablename__ = 'borrow_request'

    id = db.Column(db.Integer, primary_key=True)
    book_id = db.Column(db.Integer, db.ForeignKey('book.id'), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    processed_by = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)
    status = db.Column(db.String(20), default='pending')
    request_time = db.Column(db.DateTime, default=datetime.utcnow)
    process_time = db.Column(db.DateTime)
    notes = db.Column(db.Text)

    # 统一关系定义
    book = db.relationship(
        'Book',
        back_populates='book_borrow_requests',
        foreign_keys=[book_id]
    )
    requester = db.relationship(
        'User',
        back_populates='submitted_borrow_requests',
        foreign_keys=[user_id]
    )
    approver = db.relationship(
        'User',
        back_populates='processed_borrow_requests',
        foreign_keys=[processed_by]
    )

    def __repr__(self):
        return f"<BorrowRequest #{self.id}>"


class Announcement(db.Model):
    """公告模型"""
    __tablename__ = 'announcement'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False, index=True, comment='标题')
    content = db.Column(db.Text, nullable=False, comment='内容')
    created_at = db.Column(db.DateTime, default=datetime.utcnow,
                         comment='创建时间')
    is_active = db.Column(db.Boolean, default=True, comment='是否激活')
    priority = db.Column(db.Integer, default=0, comment='优先级')

    def __repr__(self):
        return f"<Announcement {self.title}>"

class Notification(db.Model):
    """通知模型"""
    __tablename__ = 'notification'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    title = db.Column(db.String(100), nullable=False, comment='标题')
    message = db.Column(db.Text, nullable=False, comment='消息内容')
    is_read = db.Column(db.Boolean, default=False, comment='是否已读')
    created_at = db.Column(db.DateTime, default=datetime.utcnow,
                         comment='创建时间')
    type = db.Column(db.String(50), nullable=False,
                   comment='类型: return_request/reservation等')

    # 关系定义
    receiver = db.relationship(
        'User',
        back_populates='user_notifications',
        foreign_keys=[user_id]
    )

    def __repr__(self):
        return f"<Notification {self.title}>"


